import { defineStore } from 'pinia'
import axios from 'axios'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: (() => {
      const storedAuth = localStorage.getItem('authStore');
      return storedAuth ? JSON.parse(storedAuth).user : null;
    })(),
    token: localStorage.getItem('token') || null,
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
  },

  actions: {
    async login(username, password) {
      try {
        const response = await axios.post('/api/auth/login', {
          username,
          password
        })
        
        const { token, user: userData } = response.data
        // 注意：后端返回的用户数据在 user.user 中
        const actualUser = userData.user || userData
        this.token = token
        this.user = actualUser
        
        // 保存token和用户信息到localStorage
        localStorage.setItem('token', token)
        localStorage.setItem('authStore', JSON.stringify({ user: actualUser }))
        
        // 设置axios默认请求头
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
        
        return { token, user: actualUser }
      } catch (error) {
        console.error('Login error:', error)
        throw error
      }
    },

    async register(userData) {
      try {
        const response = await axios.post('/api/auth/register', userData)
        return response.data
      } catch (error) {
        console.error('Registration error:', error)
        throw error
      }
    },

    logout() {
      this.user = null
      this.token = null
      
      // 清除localStorage中的token和用户信息
      localStorage.removeItem('token')
      localStorage.removeItem('authStore')
      
      // 移除axios默认请求头
      delete axios.defaults.headers.common['Authorization']
    },

    async fetchUser() {
      if (!this.token) {
        throw new Error('No token available')
      }
      
      try {
        const response = await axios.get('/api/auth/profile')
        this.user = response.data
        return response.data
      } catch (error) {
        console.error('Failed to fetch user:', error)
        this.logout() // 如果获取用户信息失败，执行登出
        throw error
      }
    }
  }
})